"""
解释方差 = 1 - var(y_true - y_pred) / var(y)
"""
import numpy as np
from sklearn.metrics import explained_variance_score


def get_data():
    """

    :return:
    """
    y_true = [3, -0.5, 2, 7]
    y_pred = [2.5, 0.0, 2, 8]
    return y_true, y_pred


def compute_ev(y_true, y_pred):
    """

    :param y_true:
    :param y_pred:
    :return:
    """
    molecular = np.var(np.array(y_true) - np.array(y_pred))
    denominator = np.var(y_true)

    return 1 - molecular / denominator


def run():
    """

    :return:
    """
    y_true, y_pred = get_data()

    # 自己算
    my_ev = compute_ev(y_true=y_true, y_pred=y_pred)

    ev = explained_variance_score(y_true=y_true, y_pred=y_pred)

    print('my: {}, sklearn: {}'.format(my_ev, ev))


if __name__ == '__main__':
    run()
